package io.dcloud.uniplugin.bc;


import android.app.ActivityManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import tech.brainco.crimsonsdk.CrimsonDevice;
import tech.brainco.crimsonsdk.CrimsonDeviceListener;
import tech.brainco.trainsdk.BcTrainPlugin;
import tech.brainco.trainsdk.api.BcTrainDeviceListener;
import tech.brainco.trainsdk.api.BcTrainDownloadListener;
import tech.brainco.trainsdk.api.BcTrainLoadListListener;
import tech.brainco.trainsdk.api.BcTrainModuleInitListener;
import tech.brainco.trainsdk.api.device.BcDeviceListener;
import tech.brainco.trainsdk.api.device.BcDeviceWrapper;
import tech.brainco.trainsdk.model.BcTrainInfo;
import tech.brainco.trainsdk.utils.BcLogger;
import uni.dcloud.io.uniplugin_module.R;

public class TrainEntryActivity extends AppCompatActivity {
    private TrainListAdapter deviceListAdapter;
    private final ArrayList<BcTrainInfo> data = new ArrayList<>();

    BcTrainDeviceListener deviceListener = null;

    private int duration = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_train_entry);

        RecyclerView trainListView = findViewById(R.id.train_list);
        trainListView.setHasFixedSize(true);
        deviceListAdapter = new TrainListAdapter(this);
        trainListView.setAdapter(deviceListAdapter);
        trainListView.setLayoutManager(new GridLayoutManager(this, 3));

        CrimsonDevice device = GlobalDevice.device;
        if (device == null) {
            Toast.makeText(this, "未连接设备，初始化失败", Toast.LENGTH_SHORT).show();
            return;
        }
        if (BcTrainPlugin.getInstance().isInited()) {
            BcTrainPlugin.getInstance().loadTrainList(new TrainLoadListListener(TrainEntryActivity.this));
//            mockData();
        } else {
            BcTrainPlugin.getInstance().init(this.getApplicationContext(), "demo_NYYfnaBkqxEqews48dsmssk4VqJn6qdC", new BcTrainModuleInitListener() {
                @Override
                public void onInited() {
                    BcLogger.d("TrainEntryActivity", "onInited");
                    BcTrainPlugin.getInstance().loadTrainList(new TrainLoadListListener(TrainEntryActivity.this));

                    ActivityManager.TaskDescription taskDescription = new ActivityManager.TaskDescription("新的任务名称");
                    setTaskDescription(taskDescription);

//                    mockData();
                }

                @Override
                public void onError(String message) {
                    BcLogger.d("TrainEntryActivity", "onError " + message);
                }
            });
        }
        BcDeviceWrapper deviceWrapper = new DeviceWrapper(device);
        deviceListener = BcTrainPlugin.getInstance().createDeviceListener(deviceWrapper);
        DeviceListener listener = new DeviceListener(deviceListener);
        device.setListener(listener);

        //自定义logger处理器
//        BcLogger.listener = new BcLoggerListener() {
//            @Override
//            public void onLogD(String message) {
//                Log.d("TrainEntryActivity", message);
//            }
//
//            @Override
//            public void onLogW(String message) {
//                Log.w("TrainEntryActivity", message);
//            }
//        };
    }

    private void mockData() {
        ArrayList<BcTrainInfo> mock = new ArrayList<>();
        mock.add(new BcTrainInfo("神秘森林", 10116, "https://focus-xin.brainco.cn/course/banner/large/10116_new.png", 1));
        mock.add(new BcTrainInfo("超级特工", 12015, "https://focus-xin-public.oss-cn-hangzhou.aliyuncs.com/course/banner/large/12015.png", 5));
        mock.add(new BcTrainInfo("奶油蛋糕", 12040, "https://focus-xin.brainco.cn/course/banner/large/12040.png", 5));
        mock.add(new BcTrainInfo("异形舒尔特", 12022, "https://focus-xin.brainco.cn/course/banner/large/12022.png", 10));
        onLoadSuccess(mock);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_train_entry, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_duration_30s) {
            duration = 30;
        } else if (item.getItemId() == R.id.action_duration_60s) {
            duration = 60;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void onLoadError(String reason) {
        Toast.makeText(this, "加载失败：" + reason, Toast.LENGTH_SHORT).show();
    }

    private void onLoadSuccess(List<BcTrainInfo> list) {
        data.addAll(list);
        deviceListAdapter.notifyDataSetChanged();
    }

    private final Set<Integer> downloadedCourseIds = new HashSet<>();
    private final Set<Integer> downloadingCourseIds = new HashSet<>();
    private final Set<Integer> notDownloadedCourseIds = new HashSet<>();

    private void onTrainClick(BcTrainInfo info, boolean withIntro) {
        //1 检查头环是否佩戴 2跳转训练页面
        if (!deviceListener.isContacted()) {
            Toast.makeText(this, "头环未佩戴", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!BcTrainPlugin.getInstance().isInited()) {
            Toast.makeText(this, "模块未初始化完成", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(this, TrainActivity.class);
        intent.putExtra("courseId", info.courseId);
        intent.putExtra("stage", info.stage);
        intent.putExtra("withIntro", withIntro);
        intent.putExtra("duration", duration);
        intent.putExtra("bestScore", 100);
        startActivity(intent);
    }

    public static class TrainListAdapter extends RecyclerView.Adapter<TrainListAdapter.TrainViewHolder> {
        private final TrainEntryActivity entryActivity;

        public TrainListAdapter(TrainEntryActivity entryActivity) {
            this.entryActivity = entryActivity;
        }

        @NonNull
        @Override
        public TrainViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_train, parent, false);
            RecyclerView.LayoutParams layoutParams = new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins(8, 8, 8, 8);
            view.setLayoutParams(layoutParams);
            return new TrainViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull TrainViewHolder holder, int position) {
            BcTrainInfo info = entryActivity.data.get(position);
            holder.nameTextView.setText(info.name);
            Glide.with(holder.itemView.getContext())
                    .load(info.banner)
                    .into(holder.bannerView);
            holder.levelTextView.setText("最大关卡" + info.maxStage);
            //create array by maxLevel
            final ArrayList<String> levels = new ArrayList<>();
            for (int i = 0; i < info.maxStage; i++) {
                levels.add("关卡" + (i + 1));
            }
            ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(entryActivity, android.R.layout.simple_spinner_item, levels);
            spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            holder.levelSpinner.setAdapter(spinnerAdapter);
            holder.levelSpinner.setSelection(info.stage - 1);
            holder.levelSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                    info.onLevelSelected(i + 1);
                }

                @Override
                public void onNothingSelected(AdapterView<?> adapterView) {

                }
            });
            holder.introButton.setOnClickListener(v -> entryActivity.onTrainClick(info, true));
            holder.gameButton.setOnClickListener(v -> entryActivity.onTrainClick(info, false));

            //下载相关，目前仅h5游戏支持下载，如果要支持本地下载的游戏包进行训练，需要设置支持localhost的http
            //如果有本地游戏包，则启动本地http服务，没有则使用在线游戏
            int courseId = info.courseId;
            boolean downloaded = entryActivity.downloadedCourseIds.contains(courseId);
            boolean notDownloaded = entryActivity.notDownloadedCourseIds.contains(courseId);
            boolean downloading = entryActivity.downloadingCourseIds.contains(courseId);
            holder.downloadButton.setText(downloaded ? "清除游戏包" : (notDownloaded ? "去下载" : downloading ? "下载中" : "检查下载"));
            holder.downloadButton.setOnClickListener((v) -> {
                if (downloaded) {
                    entryActivity.downloadedCourseIds.remove(courseId);
                    entryActivity.notDownloadedCourseIds.add(courseId);
                    BcTrainPlugin.getInstance().clearDownloaded(courseId);
                    notifyDataSetChanged();
                } else if (notDownloaded) {
                    entryActivity.notDownloadedCourseIds.remove(courseId);
                    entryActivity.downloadingCourseIds.add(courseId);
                    notifyDataSetChanged();
                    BcTrainPlugin.getInstance().preDownload(courseId, new BcTrainDownloadListener() {
                        @Override
                        public void onDownloaded() {
                            BcLogger.d("TrainEntryActivity", "onDownloaded");
                            entryActivity.downloadingCourseIds.remove(courseId);
                            entryActivity.downloadedCourseIds.add(courseId);
                            notifyDataSetChanged();
                        }

                        @Override
                        public void onDownloadError(String reason) {
                            Toast.makeText(entryActivity, "下载失败:"+reason, Toast.LENGTH_SHORT).show();
                            entryActivity.notDownloadedCourseIds.add(courseId);
                            entryActivity.downloadingCourseIds.remove(courseId);
                        }
                    });
                } else if (downloading) {
                } else {
                    BcTrainPlugin.getInstance().checkDownloadValid(courseId, new BcTrainDownloadListener() {
                        @Override
                        public void onCheckResult(boolean isValid) {
                            if (isValid) {
                                entryActivity.downloadedCourseIds.add(courseId);
                            } else {
                                entryActivity.notDownloadedCourseIds.add(courseId);
                            }
                            notifyDataSetChanged();
                        }
                    });
                }
            });
        }

        @Override
        public int getItemCount() {
            return entryActivity.data.size();
        }

        static class TrainViewHolder extends RecyclerView.ViewHolder {
            ImageView bannerView;
            TextView nameTextView;
            TextView levelTextView;
            Spinner levelSpinner;
            Button introButton;
            Button gameButton;
            Button downloadButton;

            public TrainViewHolder(@NonNull View itemView) {
                super(itemView);
                bannerView = itemView.findViewById(R.id.item_train_banner);
                nameTextView = itemView.findViewById(R.id.item_train_name);
                levelTextView = itemView.findViewById(R.id.item_train_maxLevel);
                levelSpinner = itemView.findViewById(R.id.item_train_spinner);
                introButton = itemView.findViewById(R.id.item_button_intro);
                gameButton = itemView.findViewById(R.id.item_button_game);
                downloadButton = itemView.findViewById(R.id.item_button_download);
            }
        }
    }

    static class TrainLoadListListener implements BcTrainLoadListListener {
        TrainEntryActivity outerClass;

        public TrainLoadListListener(TrainEntryActivity outerClass) {
            this.outerClass = outerClass;
        }

        @Override
        public void onSuccess(List<BcTrainInfo> list) {
            outerClass.onLoadSuccess(list);
        }

        @Override
        public void onError(@NonNull String errorCode, @Nullable String errorMessage, @Nullable Object errorDetails) {
            outerClass.onLoadError(errorCode);
        }
    }

    private static class DeviceListener extends CrimsonDeviceListener {
        final BcDeviceListener listener;

        public DeviceListener(BcDeviceListener listener) {
            this.listener = listener;
        }

        @Override
        public void onConnectivityChange(int connectivity) {
            listener.onConnectivityChange(connectivity);
        }

        @Override
        public void onContactStateChange(int state) {
            listener.onContactStateChange(state);
        }

        @Override
        public void onOrientationChange(int orientation) {
            listener.onOrientationChange(orientation);
        }

        @Override
        public void onAttention(float attention) {
            listener.onAttention(attention);
        }

        @Override
        public void onMeditation(float meditation) {
            listener.onMeditation(meditation);
        }
    }

}